<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/10/19
 * Time: 11:58
 */

namespace Biz\model\activity;

use Doraemon\pockets\datebase\BaseDbModel;

class GroupBuy extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'group_buy';


    const COUNT_TYPE_ADM = 'add_count';
	const COUNT_TYPE_BUYER = 'current_count';

    const STATUS_NORMAL = 1;
    const STATUS_DELECT = 9;

    const STATUS_GROUP_SUCCESS = 2; //拼团成功

	const STATUS_GROUP_SUCCESS_CURRENT = 3; //刚刚拼团成功


	public static $status_descs = [
		self::STATUS_NORMAL => [
			'status' => self::STATUS_NORMAL,
			'status_desc' => '团购进行中'
		],
		self::STATUS_GROUP_SUCCESS => [
			'status' => self::STATUS_GROUP_SUCCESS,
			'status_desc' => '拼团成功，待发货'
		],
		self::STATUS_DELECT => [
			'status' => self::STATUS_DELECT,
			'status_desc' => '未成团，退款中'
		],
		self::STATUS_GROUP_SUCCESS_CURRENT => [
			'status' => self::STATUS_GROUP_SUCCESS_CURRENT,
			'status_desc' => '拼团成功，待发货'
		],

	];

    public static function getInfo($where, $field = '*')
    {
        return self::get($field, $where);
    }

    public static function getInfos($where, $field = '*', $isMaster = false)
    {
    	if ($isMaster) {
			return self::select_master($field, $where);
		}
        return self::select($field, $where);
    }

    public static function getList($where ,$page, $pagesize = 20)
	{
		$where = array_merge($where, [
			'status' => self::STATUS_NORMAL,
			'ORDER' => ['end_time' => 'DESC'],
			'LIMIT' => [($page - 1) * $pagesize, $pagesize]
		]);
		return ['list' => self::select('*', $where), 'count' => self::count($where)];

	}

	public static function increCounter($groupIds, $counterField = self::COUNT_TYPE_BUYER, $increCounter = 1)
	{
		return self::update([
			$counterField. "[+]" =>  $increCounter
		], [
			'id' => $groupIds,
			'status' => self::STATUS_NORMAL
		]) -> rowCount();

	}

    public static function saveData($data, $admin_uid)
	{
		$id  =  $data['id'];
		$data = [
			'shop_id' => $data['shop_id'],
			'goods_id' => $data['goods_id'],
			'start_time' => $data['start_time'],
			'end_time' => $data['end_time'],
			'min_count' => $data['min_count'],
			'addtime' => date('Y-m-d H:i:s'),
			'admin_id' => $admin_uid
		];
		if (isset($id) && $id) {
			self::update($data, [
				'id' => $id
			]);
		} else {
			self::insert($data);
			return self::id();
		}
		return $id;

	}
}